// 网关配置的前缀
var account_server = "/accountSer"

// let userId = "9999999"
let userId = ""

// 初始值
var duty_init = ""
var name_init = "";
var email_init = "";
var phone_init = "";

// 文本框中的值（随输入变化）
var duty_value = "";
var name_value = "";
var email_value = "";
var phone_value = "";
let company_value = "";

// 图片地址
var photo_path = "";

let Authorization = "";
let refreshToken = "";

// 加载页面时读取后台的 ip
window.onload = function (){
    let accountStatus = $("#accountStatus").html();
    if(accountStatus !== "正常"){
        $("#forbidden").removeAttr("hidden");
    }

    $.ajaxSettings.async = false;
    $.getJSON("/js/properties.json", function (data) {
        account_server = data.accountServer;
    });
    // 获取令牌
    Authorization = getCookie("Authorization")
    refreshToken = getCookie("refreshToken")
    userId = $("#userId").html();
    $(".userId").val(userId);
    getBaseInfo();
}


function getBaseInfo() {
    $.ajax({
        type: "get",
        async: false,
        url: account_server + "/account/baseInfo?userId="+userId,
        headers: {
            "Authorization": Authorization,
            "refreshToken": refreshToken,
        },
        success: function (data) {
            unauthorized(data);
            let baseInfo = data.datas;

            if (baseInfo.photo !== null && baseInfo.photo !== ""){
                $(".create-photo-left").css("background-image", "url(" + baseInfo.photo + ")")
                    .css("background-repeat", "no-repeat")
                    .css('background-size', '100% 100%');
                $("#photo-logo *").hide();
            }

            if (baseInfo.companyName === "" || baseInfo.companyName === null){
                $("#company").val("---");
            }else {
                $("#company").val(baseInfo.companyName);
                company_value = baseInfo.companyName;
            }
            $("#position").val(baseInfo.role);
            if (baseInfo.hrStatus === "" ||
                baseInfo.hrStatus === null){
                $("#status").val(baseInfo.accountStatus);
            }else{
                $("#status").val(baseInfo.hrStatus);
            }
            $("#duty").val(baseInfo.duty);
            $("#name").val(baseInfo.userName);
            $("#email").val(baseInfo.email);
            $("#phone").val(baseInfo.phone);

            duty_init = baseInfo.duty;
            name_init = baseInfo.userName;
            email_init = baseInfo.email;
            phone_init = baseInfo.phone;
        },
        error: function (err) {
            console.log(err);
        }
    });
}

// 上传照片 部分
$("input[name='photo']").change(function (event) {
    // 获取图片元素
    var ele = event.target;

    if (!/.(gif|jpg|jpeg|png|GIF|JPG|bmp)$/.test(ele.value)) {
        alert("图片类型必须是.gif,jpeg,jpg,png,bmp中的一种");
        return false;
    }

    var files = ele.files;
    if (files && files.length <= 0) {
        alert("出错了，请重新上传。")
    }

    var file = files[0];
    if (file.size > 1024 * 100) {
        alert('照片大小不能超过 100KB!');
        return false;
    }

    // 获取目前上传的文件
    console.log("上传了照片");

    var path = URL.createObjectURL(file);
    photo_path = path;
    $(".create-photo-left").css("background-image", "url(" + path + ")")
        .css("background-repeat", "no-repeat")
        .css('background-size', '100% 100%');
    $("#photo-logo *").hide();

    // 将文件传到后端
    $('#uploadPhoto').ajaxSubmit({
        datatype: 'json',
        success: function (res) {
            cocoMessage.info(2000, "图片上传成功", function () {
            });
        },
        error: function (res) {
            cocoMessage.error(2000, "图片上传出错，请重试", function () {
            });
        }
    });
});

// 提交修改
// 修改提交按钮状态
// isSubmit : 是否 可以 提交
function change_but_status(isSubmit) {
    if (isSubmit) {// 可以提交
        $("#submit").attr('disabled', false);
        $("#submit").css('background-color', '#1dae0e');
        $(".tips").attr('hidden', true);
    } else {// 不可提交
        $("#submit").attr('disabled', true);
        $("#submit").css('background-color', '#808080c2');
        $(".tips").attr('hidden', false);
    }
}

// 判断文本框中的值是否修改，修改了则可以提交


$('.baseInfo').change(function () {
    duty_value = $('#duty').val();
    name_value = $('#name').val();
    email_value = $('#email').val();
    phone_value = $('#phone').val();

    // 如果当前值和初始值一样，则不可提交
    if (duty_value === duty_init &&
        name_value === name_init &&
        email_value === email_init &&
        phone_value === phone_init) {

        change_but_status(false);
        return;
    }

    // 如果值不一样了，可提交
    change_but_status(true);
});

// 修改图片了，则可以直接提交
$('.create-photo-left').change(function () {
    change_but_status(true);
    $(".tips").html("照片已修改，可以提交")
        .attr('hidden', false);
});


$('#submit').click(function (argument) {
    $.ajax({
        type: "POST",
        async: false,
        url: account_server + "/account/baseInfo",
        headers: {
            "Content-Type": "application/json",
            "Authorization": Authorization,
            "refreshToken": refreshToken,
        },
        data: JSON.stringify({
            "userId": userId,
            "userName": name_value,
            "phone": phone_value,
            "email": email_value,
            "duty": duty_value,
            "companyName": company_value,
        }),
        success: function (data) {
            if (data.resp_code === 0) {
                // 成功
                cocoMessage.info(2000, data.resp_msg, function () {
                });
                // 提交完后，重置初始值
                duty_init = duty_value;
                name_init = name_value;
                email_init = email_value;
                phone_init = phone_value;

                // 提交完后，设置按钮为不可提交
                change_but_status(false);
                $(".tips").html()
                    .attr('hidden', true);
            } else {
                // 失败
                cocoMessage.error(2000, data.resp_msg, function () {
                    console.log(data.resp_msg);
                });
            }
        },
        error: function (err) {
            // 异常
            cocoMessage.error(2000, err.statusText, function () {
                console.log(err);
            });
        }
    })
    return false;
})
